import { Injectable } from '@angular/core';
import { HttpEvent, HttpHandler, HttpInterceptor, HttpRequest, HttpResponse, HttpHeaders } from '@angular/common/http';
import { Observable } from 'rxjs/Observable';
import { AuthService } from './auth.service';
import { tap } from "rxjs/operators";
import { HttpRes } from "../model/HttpRes";

/**
 * 拦截器
 */
@Injectable()
export class InterceptorService implements HttpInterceptor {

  constructor(private auth: AuthService) { }

  intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {

    // 获取token令牌;
    const authToken = this.auth.token;
    let headers = new HttpHeaders();
    if (this.auth.token.token) {
      headers = headers.append('token', this.auth.token.token).append('userId', this.auth.token.userid);
    }
    // 设置添加token令牌后的请求 没有登录时为空;
    const authReq = req.clone({
      headers: headers
    });

    // observable对象上的pipe管道可以用来监听返回的response 用来设置统一的错误处理;
    // (后续加全局的toast);
    return next.handle(authReq).pipe(
      tap(
        data => {
        }
      )
    );
  }

}
